package com.yinxing.framework.shiro.interceptor;

import com.yinxing.framework.shiro.exception.RequiresPermissionException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.aop.PermissionAnnotationHandler;
import org.apache.shiro.subject.Subject;

import java.lang.annotation.Annotation;
import java.util.Arrays;

public class MyPermissionAnnotationHandler extends PermissionAnnotationHandler {

    public void assertAuthorized(Annotation a) throws AuthorizationException {
        if (!(a instanceof RequiresPermissions)) return;

        RequiresPermissions rpAnnotation = (RequiresPermissions) a;
        String[] perms = getAnnotationValue(a);
        Subject subject = getSubject();

        boolean hasPermission = false;

        if (perms.length == 1) {
            hasPermission = subject.isPermitted(perms[0]);
        }
        if (Logical.AND.equals(rpAnnotation.logical())) {
            hasPermission = getSubject().isPermittedAll(perms);
        }
        if (Logical.OR.equals(rpAnnotation.logical())) {
            for (String permission : perms) if (getSubject().isPermitted(permission)) hasPermission = true;
        }

        if(!hasPermission) {
            String msg = "用户不具备所需权限" + Arrays.toString(perms) + "逻辑:" + rpAnnotation.logical();
            throw new RequiresPermissionException(msg);
        }
    }

}
